package com.mytijian.openapi.adapter.dianping.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mytijian.openapi.adapter.dianping.consts.DzopenConsts;
import com.mytijian.openapi.adapter.dianping.param.DzCounterParam;
import com.mytijian.openapi.adapter.dianping.result.DzCounterResult;
import com.mytijian.openapi.adapter.dianping.result.DzPeriodInfo;
import com.mytijian.openapi.adapter.dianping.service.DzopenCounterService;
import com.mytijian.openapi.core.client.IOpenAPIClient;
import com.mytijian.openapi.core.client.result.CounterInfo;
import com.mytijian.openapi.core.client.result.CounterResult;
import com.mytijian.openapi.core.client.result.PeriodInfo;
import com.mytijian.openapi.core.model.AppConfig;
import com.mytijian.openapi.core.service.OpenApiAppConfigService;
import com.mytijian.utils.DateUtils;

@Service("dzopenCounterService")
public class DzopenCounterServiceImpl implements DzopenCounterService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private OpenApiAppConfigService openApiAppConfigService;

	@Autowired
	private IOpenAPIClient client;

	@Override
	public List<DzCounterResult> getCounter(DzCounterParam param) {

		AppConfig config = openApiAppConfigService.getConfig(DzopenConsts.AppName);
		Integer hospitalId = Integer.parseInt(param.getAppShopId());

		Date start = DateUtils.parse(param.getBookdate());
		int days = Integer.parseInt(param.getDays());
		days = days-1;
		Date end = new Date(start.getTime() + 86400L * 1000 * days);

		CounterResult r = client.getCounter(config, hospitalId, DateUtils.format(start), DateUtils.format(end));

		List<CounterInfo> dayCapacitys = r.getDayCapacitys();

		// 点评人数数据 需要把 开放平台的两层数据转换为一层
		List<DzCounterResult> results = new ArrayList<>();
		if (dayCapacitys != null) {
			for (CounterInfo CounterInfo : dayCapacitys) {

				List<PeriodInfo> periods = CounterInfo.getPeriodCapacitys();

				for (PeriodInfo period : periods) {

					DzCounterResult result = new DzCounterResult();
					result.setBooktime(CounterInfo.getDateStr());
					result.setDuration("0");
					DzPeriodInfo dzPeriod = new DzPeriodInfo();

					dzPeriod.setApp_period_id(String.valueOf(period.getPeriod()));
					dzPeriod.setPeriod_name(period.getPeriodName());

					DzPeriodInfo info = new DzPeriodInfo();
					info.setApp_period_id(String.valueOf(period.getPeriod()));
					info.setPeriod_name(period.getPeriodName());
					if (period.getUsable()) {
					result.setRemaincount(String.valueOf(period.getAvailableNum()));
					} else {
						result.setRemaincount("0");
					}
					result.setPeriod(dzPeriod);
					results.add(result);

				}
			}
		}
		return results;
	}

}
